//
//  MSSignUpVC.m
//  MS
//
//  Created by Yuan on 13-3-26.
//  Copyright (c) 2013年 He Yuan. All rights reserved.
//

#import "MSSignUpVC.h"
#import "MSAppDelegate.h"
#import "MSImproveUserInfoVC.h"
#import "MSLogInCell.h"
#import "UIDevice+IdentifierAddition.h"

@interface MSSignUpVC ()<UITableViewDataSource,UITableViewDelegate>
{
    UITableView *listTableView;
    BOOL isSelectUploadImage;
    SignInType signInType;
}
@property(nonatomic,retain) UITableView *listTableView;

@end

@implementation MSSignUpVC
@synthesize listTableView;
 
- (id)init
{
    self = [super init];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)loadView
{
    [super loadView];
        
    CGRect tableViewFrame = CGRectMake(5,10, self.view.frame.size.width-10, 220);
    listTableView = [[UITableView alloc]initWithFrame:tableViewFrame style:UITableViewStyleGrouped];
    listTableView.delegate = self;
    listTableView.dataSource = self;
    listTableView.backgroundColor = [UIColor clearColor];
    listTableView.backgroundView = nil;
    [self.view addSubview:listTableView];
    
    UILabel *lbl = [MSTool createLable:CGRectMake(0,listTableView.frame.size.height + listTableView.frame.origin.y+10, self.view.frame.size.width, 30)];
    [lbl setText:HYLocalizedString(@"填完后请选择身份完成注册")];
    [self.view addSubview:lbl];
    [lbl setTextAlignment:UITextAlignmentCenter];
    
    UIButton *personBtn = [MSTool createButton:CGRectMake(22,lbl.frame.size.height + lbl.frame.origin.y + 15,128,32) action:@selector(personSignUp:) delegate:self];
    [personBtn setImage:[UIImage imageNamed:@"signup_person"] forState:UIControlStateNormal];
    [self.view addSubview:personBtn];

    UIButton *hairdressBtn = [MSTool createButton:CGRectMake(172,lbl.frame.size.height + lbl.frame.origin.y + 15,128,32) action:@selector(hairDressSignUp:) delegate:self];
    [hairdressBtn setImage:[UIImage imageNamed:@"signup_haridress"] forState:UIControlStateNormal];
    [self.view addSubview:hairdressBtn];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setTitle:HYLocalizedString(@"用户注册") showBackButton:YES];
        
	// Do any additional setup after loading the view.
}


-(void)personSignUp:(UIButton *)btn
{
    [self startSignUp:SignInTypeCustomer];
}

-(void)hairDressSignUp:(UIButton *)btn
{
    [self startSignUp:SignInTypeHairDresser];
}

-(void)startSignUp:(SignInType)type
{
    MSLogInCell *accountcell = (MSLogInCell *)[listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    NSString *account = accountcell.txtField.text;
    
    MSLogInCell *pwdcell = (MSLogInCell *)[listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    NSString *pwd = pwdcell.txtField.text;

    MSLogInCell *emailcell = (MSLogInCell *)[listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
    NSString *email = emailcell.txtField.text;

    if ([account length]<1 || [pwd length]<1 || [email length]<1)
    {
        [MSTool showAlertTitle:HYLocalizedString(@"提示") message:HYLocalizedString(@"数据填写不完整！")];
        return;
    }
    
    if ([account length]<2)
    {
        [MSTool showAlertTitle:HYLocalizedString(@"提示") message:HYLocalizedString(@"亲，您的昵称太短了!")];
        return;
    }
    
    if ([pwd length]<6)
    {
        [MSTool showAlertTitle:HYLocalizedString(@"提示") message:HYLocalizedString(@"密码不能少于6位!")];
        return;
    }
    
    if (![MSTool checkEmailValue:email])
    {
        [MSTool showAlertTitle:HYLocalizedString(@"提示") message:HYLocalizedString(@"Email格式不对!")];
        return;
    }
    
    signInType = type;
    
    NSString *udid = [[UIDevice currentDevice] uniqueDeviceIdentifier];
    
    NSDictionary *p =  [NSDictionary dictionaryWithObjectsAndKeys:
                        account,@"user_name",
                        email,@"email",
                        pwd,@"password",
                        pwd,@"confirm_password",
                        [NSNumber numberWithInt:type],@"gid",
                        udid,@"udid",
                        [[MSSetting sharedSetting]getDeviceToken],@"token",
                        nil];
    [WebService  getRequestAction:APIUserRegister
                            param:p
                          success:^(NSDictionary *info,NSError *error)
     {
         if (error == nil)
         {
             HYLog(@"%@",info);
             if (info)
             {
                 [[MSAppDelegate sharedAppDelegate]handleUserInfo:info password:pwd];
               
                 //判断是否需要上传图片
                 if (isSelectUploadImage)
                 {
                     [self startUploadImage];
                 }
                 else
                 {
                     if (signInType == SignInTypeCustomer) //个人用户注册
                     {
                         [[MSAppDelegate sharedAppDelegate]dismissViewControl];
                     }
                     else if(signInType == SignInTypeHairDresser) //发型师注册，跳转到完善用户信息界面
                     {
                         [self loadViewController:NSStringFromClass([MSImproveUserInfoVC class])];
                     }
                 }
             }
         }
         [MSTool showError:error];
     } failure:^(id info ,NSError *error){
         [MSTool showError:error];
     } progress:self.navigationController.view];
}

-(void)startUploadImage
{    
    NSDictionary *p = [NSDictionary dictionaryWithObjectsAndKeys:
                       APISetUserAvatar,@"action",[[MSSetting sharedSetting] getAccountID],@"uid", nil];
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:3 inSection:0];
    UITableViewCell *cell = [self.listTableView cellForRowAtIndexPath:indexPath];
    UIImageView *imgView =  (UIImageView *)cell.accessoryView;
    
    [WebService uploadImage:imgView.image param:p labelText:HYLocalizedString(@"上传头像") success:^(NSDictionary *info,NSError *error)
     {
         if (signInType == SignInTypeCustomer) //个人用户注册
         {
             [[MSAppDelegate sharedAppDelegate]dismissViewControl];
         }
         else if(signInType == SignInTypeHairDresser) //发型师注册，跳转到完善用户信息界面
         {
             [self loadViewController:NSStringFromClass([MSImproveUserInfoVC class])];
         }
     } failure:^(id info ,NSError *error){
         [MSTool showAlert:error.localizedDescription];
     }];
}

#pragma mark -UITableViewDataSource

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 4;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50.0f;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *identifier=@"Login";
    MSLogInCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell)
    {
        cell= [[MSLogInCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
    }
    cell.textLabel.textColor = [UIColor grayColor];
    cell.textLabel.text  = @"";
    cell.txtField.hidden = NO;
    NSString *imageName = @"";
    NSString *placeHolder = @"";
    switch (indexPath.row)
    {
        case 0:
            placeHolder = HYLocalizedString(@"请输入用户名");
            imageName = @"smile";
            cell.txtField.secureTextEntry = NO;
            cell.accessoryView = nil;
            break;
        case 1:
            placeHolder = HYLocalizedString(@"请输入密码");
            imageName = @"lock";
            cell.txtField.secureTextEntry = YES;
            cell.accessoryView = nil;
            break;
        case 2:
            placeHolder = HYLocalizedString(@"请输入Email地址");
            imageName = @"email";
            cell.txtField.secureTextEntry = NO;
            cell.accessoryView = nil;
            break;
        case 3:
            placeHolder = HYLocalizedString(@"");
            imageName = @"photo";
            cell.txtField.secureTextEntry = NO;
            cell.txtField.hidden = YES;
            cell.textLabel.text = HYLocalizedString(@"上传图像");
            break;
        default:
            break;
    }
    cell.txtField.placeholder = placeHolder;
    cell.imageName = imageName;

    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    if (indexPath.row == 3)
    {
        [listTableView.visibleCells makeObjectsPerformSelector:@selector(resignFirstResponder)];
        UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:HYLocalizedString(@"取消") destructiveButtonTitle:nil otherButtonTitles:HYLocalizedString(@"拍照"),HYLocalizedString(@"从相册选择"), nil];
        sheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
        [sheet showInView:self.navigationController.view];
    }
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == actionSheet.cancelButtonIndex)
    {
        return;
    }
    else if(buttonIndex == 0)
    {
        [self performSelector:@selector(takePhoto) withObject:nil afterDelay:0.0];
    }
    else if(buttonIndex == 1)
    {
        [self performSelector:@selector(openPhotoLibrary) withObject:nil afterDelay:0.0];
    }
}

-(void)openPhotoLibrary
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentModalViewController:picker animated:YES];
}

//take a photo from camera
-(void)takePhoto
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
	{
		UIImagePickerController *picker = [[UIImagePickerController alloc] init];
		picker.delegate = self;
		picker.allowsEditing = YES;
		picker.sourceType = UIImagePickerControllerSourceTypeCamera;
		[self presentModalViewController:picker animated:YES];
	}
    else
    {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:HYLocalizedString(@"设备不支持拍照") message:nil delegate:nil cancelButtonTitle:HYLocalizedString(@"确定") otherButtonTitles:nil, nil];
        [alert show];
    }
}


#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
	// TODO, improve change the resolution of the edited image
    //	UIImage *originalImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    UIImage *editimg = [info objectForKey:UIImagePickerControllerEditedImage];
    NSAssert(editimg != nil, @"Can't get the image!");
	if (editimg)
	{
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:3 inSection:0];
        UITableViewCell *cell = [self.listTableView cellForRowAtIndexPath:indexPath];
        UIImageView *imgView =  (UIImageView *)cell.accessoryView;
        [imgView setImage:editimg];        
        isSelectUploadImage = YES;
    }
	[picker dismissModalViewControllerAnimated:YES];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissModalViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)dealloc
{
    listTableView = nil;
}

@end
